package com.markerhub.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.markerhub.entity.User;
import com.markerhub.mapper.UserMapper;
import com.markerhub.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.markerhub.utils.SaltUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 关注公众号：MarkerHub
 * @since 2021-04-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
     @Autowired
     UserMapper userMapper;

     @Override
     public User finduserByUserName(String username)
     {
         QueryWrapper<User> queryWrapper=new QueryWrapper<>();
         queryWrapper.eq("username",username);
         return userMapper.selectOne(queryWrapper);
     }

     @Override
    public boolean changepassword(String username,String password)
     {
         QueryWrapper<User> qt=new QueryWrapper<>();
         qt.eq("username",username);
         User user=userMapper.selectOne(qt);
         String salt = user.getSalt();
         String newpw2 = new SimpleHash("md5",password,salt).toString();
         if(newpw2.compareTo(user.getPassword())==0)
             return false;
         user.setPassword(newpw2);
         userMapper.update(user,qt);
         return true;
     }

     @Override
    public boolean add_user(String username, String password,String nickname,String email,String avatar,String type)
     {
         User user=new User();
         QueryWrapper<User> queryWrapper=new QueryWrapper<>();
         queryWrapper.eq("username",username);
         if(userMapper.selectOne(queryWrapper)!=null)
             return false;
         user.setUsername(username);
         String salt=SaltUtils.getSalt(8);
         String newpw = new SimpleHash("md5",password,salt).toString();
         user.setPassword(newpw);
         user.setSalt(salt);
         user.setNickname(nickname);
         user.setEmail(email);
         user.setAvatar(avatar);
         user.setType(type);
         userMapper.insert(user);
         return true;
     }
}
